package com.example.nophase.activity.manager;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import com.example.nophase.R;
import com.example.nophase.activity.FlowRecordActivity;
import com.example.nophase.adapter.AdultFromProjectListAdapter;
import com.example.nophase.api.RequstCommonApi;
import com.example.nophase.base.BaseActivity;
import com.example.nophase.common.BaseCallBack;
import com.example.nophase.common.BaseResp;
import com.example.nophase.common.LoginManager;
import com.example.nophase.custom.CustomDialog;
import com.example.nophase.custom.MoneyDialog;
import com.example.nophase.custom.TextFieldDialog;
import com.example.nophase.custom.WarningDialog;
import com.example.nophase.entity.AdultMsgDTO;
import com.example.nophase.entity.ProjectDetailDTO;
import com.example.nophase.entity.SysUserVO;
import com.example.nophase.utils.HttpUtils;
import com.example.nophase.utils.WaterMarkBg;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

public class AdultFromActivity extends BaseActivity {


    @BindView(R.id.toolbar_btn)
    Button toolbarBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.adult_no)
    TextView adultNo;
    @BindView(R.id.adult_name)
    TextView adultName;
    @BindView(R.id.adult_tel)
    TextView adultTel;
    @BindView(R.id.adult_position_iv)
    ImageView adultPositionIv;
    @BindView(R.id.adult_sumMoney)
    TextView adultSumMoney;
    @BindView(R.id.adult_totalMoney)
    TextView adultTotalMoney;
    @BindView(R.id.adult_limitMoney)
    TextView adultLimitMoney;
    @BindView(R.id.adult_resignMoney)
    TextView adultResignMoney;
    @BindView(R.id.adult_project_list)
    ListView adultProjectList;
    @BindView(R.id.adult_back)
    Button adultBack;
    @BindView(R.id.adult_save)
    Button adultSave;
    @BindView(R.id.adult_from_progressbar)
    ProgressBar adultFromProgressbar;
    @BindView(R.id.adult_limit_Type)
    TextView adultLimitType;
    @BindView(R.id.content_layout)
    LinearLayout contentLayout;
    @BindView(R.id.btn_layout)
    LinearLayout btnLayout;
    @BindView(R.id.applyfor_save_btn)
    Button applyforSaveBtn;
    @BindView(R.id.adult_moneyAdd)
    TextView adultMoneyAdd;

    private AdultMsgDTO applyForDTO;
    private List<ProjectDetailDTO> projectList;
    private AdultFromProjectListAdapter adapter;
    private BigDecimal adultMoney;
    private String forkey;
    private String activityName;
    private String appType;
    private SysUserVO userVO;
    private String appRegion;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_adult_from);
        ButterKnife.bind(this);
        initData();
        setToolbar();
        applyforSaveBtn.setVisibility(View.GONE);


    }

    public void setBackground(String activity) {
        userVO = LoginManager.getUserInfo(AdultFromActivity.this);
        List<String> labels = new ArrayList<>();
        labels.add(userVO.getUsername());
        contentLayout.setBackground(new WaterMarkBg(AdultFromActivity.this, labels, -30, 18));
        String position = userVO.getMoreInfo().getPosition();
        switch (activity) {
            case "中心外联审批":
                adultPositionIv.setBackgroundResource(R.drawable.zxwl);
                break;
            case "业务/总部部门审核":
                if (!position.equals("区域项目负责人")) {
                    adultPositionIv.setBackgroundResource(R.drawable.znbmjl);
                } else {

                    adultPositionIv.setBackgroundResource(R.drawable.qyfzr);
                }
                break;
            case "分公司/副总审核":
                if (!position.equals("分公司总经理")) {

                    adultPositionIv.setBackgroundResource(R.drawable.gsfz);
                } else {
                    adultPositionIv.setBackgroundResource(R.drawable.fgsz);
                }
                break;
            case "分公司总审核":
                adultPositionIv.setBackgroundResource(R.drawable.fgsz);
                break;
            case "分公司副总审核":
                adultPositionIv.setBackgroundResource(R.drawable.gsfz);
                break;
            case "公司总审核":
                adultPositionIv.setBackgroundResource(R.drawable.zgsz);
                break;
            case "申请人申请":

                switch (position) {
                    case "区域项目负责人":
                        adultPositionIv.setBackgroundResource(R.drawable.qyfzr);
                        break;
                    case "职能中心外联部员工":
                        adultPositionIv.setBackgroundResource(R.drawable.zxwl);
                        break;
                    case "职能部门副总经理":
                        adultPositionIv.setBackgroundResource(R.drawable.gsfz);
                    case "职能部门经理":
                        adultPositionIv.setBackgroundResource(R.drawable.znbmjl);
                        break;
                }
                break;
        }


    }

    private void initData() {
        Intent intent = getIntent();
        forkey = intent.getStringExtra("forkey");
        System.out.println("forkey=======" + forkey);
        HttpUtils.getInstance().setAuthToken(LoginManager.getToken(this));
        adultFromProgressbar.setVisibility(View.VISIBLE);
        Call<BaseResp<AdultMsgDTO<ProjectDetailDTO>>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).loadTaskFrom("ANDROID", Integer.valueOf(forkey));
        call.enqueue(new BaseCallBack<BaseResp<AdultMsgDTO<ProjectDetailDTO>>>() {
            @Override
            public void onSuccess(Response<BaseResp<AdultMsgDTO<ProjectDetailDTO>>> response) throws Exception {
                if (response.body().getSuccess()) {
                    adultFromProgressbar.setVisibility(View.GONE);
                } else {
                    showDialog();
                }
                applyForDTO = response.body().getData();
                activityName = applyForDTO.getActivitiname();
                appRegion = applyForDTO.getAppRegion();
                setBackground(applyForDTO.getActivitiname());
                adultMoney = applyForDTO.getAuditMoney();
                appType = applyForDTO.getAppType();
                projectList = applyForDTO.getTyBusinessAppDetailVos();
                if (applyForDTO.getLimitType() == null) {
                    adultLimitType.setText("年初限额");
                } else {
                    adultLimitType.setText("年初限额" + "(" + applyForDTO.getLimitType() + ")");
                }
                adultTotalMoney.setText(getdivide(applyForDTO.getTotalMoney()));//累计批付金额
                adultLimitMoney.setText(getdivide(applyForDTO.getLimitMoney()));//限额
                adultResignMoney.setText(getdivide(applyForDTO.getAuditMoney()));//批付金额

                adultMoneyAdd.setText(getdivide(applyForDTO.getMoneyAdd()));//累计申请金额
                adultName.setText(applyForDTO.getAppUserName());
                adultTel.setText(applyForDTO.getAppUsertel());
                adultNo.setText(applyForDTO.getNo().toString());
                adultSumMoney.setText(getdivide(applyForDTO.getAppMoney()));

                adapter = new AdultFromProjectListAdapter(projectList, AdultFromActivity.this);
                adultProjectList.setAdapter(adapter);
                adultProjectList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        showMoneyInputDialog(position);
                    }
                });
                adultProjectList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                    @Override
                    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                        String cause = projectList.get(position).getAppReason();
                        WarningDialog dialog = new WarningDialog(AdultFromActivity.this, "申请原因", "申请原因", "关闭");
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.show();
                        dialog.setInputMsg(cause);
                        dialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                            @Override
                            public void doConfirm() {
                                dialog.dismiss();
                            }
                        });
                        return true;
                    }
                });

            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    private void showDialog() {

        LayoutInflater factory = LayoutInflater.from(this);//提示框
        final View view = factory.inflate(R.layout.dialog_layout, null);//这里必须是final的
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("提醒")//提示框标题
                .setIcon(R.drawable.apply_for_from)
                .setMessage("网络环境异常,请点击刷新")
                .setPositiveButton("刷新",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                initData();
                            }
                        }).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    private void showMoneyInputDialog(int position) {
        MoneyDialog dialog = new MoneyDialog(AdultFromActivity.this, "金额", "确定", "取消");
        dialog.setCanceledOnTouchOutside(false);
        dialog.setHintMsg("请输入批付金额");
        dialog.show();
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String money = dialog.getInputMsg();
                if (!money.equals("")) {
                    projectList.get(position).setAuditMoney(Integer.valueOf(money));
                    int summoney = 0;
                    for (ProjectDetailDTO item : projectList) {
                        summoney += item.getAuditMoney();
                    }
                    adultMoney = new BigDecimal(summoney);
                    adultResignMoney.setText(String.valueOf(adultMoney));
                    applyForDTO.setAuditMoney(adultMoney);
                    adapter.notifyDataSetChanged();
                    dialog.dismiss();
                } else {
                    dialog.dismiss();
                }

            }

            @Override
            public void doCancel() {
                dialog.dismiss();
            }
        });


    }


    private void showCauseInputDialog(int result) {
        TextFieldDialog dialog = new TextFieldDialog(AdultFromActivity.this, "审核信息", "请输入审核信息", "确认", "取消");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                String cause = dialog.getInputMsg();
                if (!cause.equals("")) {
                    applyForDTO.setAdvice(cause);
                    if (result == 1) {
                        if (activityName.equals("中心外联审批")) {

                            if (appRegion.equals("鲁班奖特殊流程")) {
                                saveAdult(result);
                            } else {

                                showManagerAdultDialog(result);
                            }

                        } else {
                            saveAdult(result);
                        }
                    } else {
                        back();
                    }
                    dialog.dismiss();
                } else {
                    Toast.makeText(AdultFromActivity.this, "请输入审批意见", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void doCancel() {
                dialog.dismiss();
            }
        });
    }


    private void back() {
        if (activityName.equals("分公司/副总审核") || activityName.equals("公司总审核")) {
            String processDefinitionId = applyForDTO.getProcessDefinitionId();
            String[] strs = processDefinitionId.split(":");
            String type = strs[0];
            int version = Integer.valueOf(strs[1]);
            switch (type) {
                case "TYWXProcess_ZLF_TWO":
                    if (version > 2) {
                        showBackTypeDialog();
                    }
                    break;
                case "TYWXProcess_HZ_TWO":
                    if (version > 2) {
                        showBackTypeDialog();
                    }
                    break;
                case "TYWXProcess":
                    if (version > 7) {
                        showBackTypeDialog();
                    }
                    break;
                default:
                    break;
            }
        } else {
            saveAdult(0);
        }
    }

    private void showManagerAdultDialog(int result) {
        CustomDialog dialog = new CustomDialog(AdultFromActivity.this, "提醒", "是否需要李总审核", "是", "否");
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                applyForDTO.setManagerAudit(true);
                saveAdult(result);
                dialog.dismiss();
            }

            @Override
            public void doCancel() {
                applyForDTO.setManagerAudit(false);
                saveAdult(result);
                dialog.dismiss();
            }
        });
    }

    private void showBackTypeDialog() {
        CustomDialog dialog = new CustomDialog(AdultFromActivity.this, "退回方式", "是否退回到发起人", "是", "否");
        dialog.show();
        dialog.setClicklistener(new CustomDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                saveAdult(2);
                dialog.dismiss();
            }

            @Override
            public void doCancel() {
                saveAdult(0);
                dialog.dismiss();
            }
        });
    }

    public void saveAdult(int result) {
        adultFromProgressbar.setVisibility(View.VISIBLE);
        applyForDTO.setResult(result);
        applyForDTO.setMainTicketId(Integer.valueOf(forkey));
        applyForDTO.setTyBusinessAppDetails(projectList);
        applyForDTO.setTyBusinessAppDetailVos(projectList);

        int adultMoney = 0;
        for (ProjectDetailDTO item : projectList) {
            adultMoney += item.getAuditMoney();
        }
        applyForDTO.setAuditMoney(new BigDecimal(adultMoney));

        Call<BaseResp<Object>> call = HttpUtils.getInstance().getApiService(RequstCommonApi.class).saveAdult("ANDROID", applyForDTO);
        call.enqueue(new BaseCallBack<BaseResp<Object>>() {
            @Override
            public void onSuccess(Response<BaseResp<Object>> response) throws Exception {
                adultFromProgressbar.setVisibility(View.GONE);
                String code = response.body().getCode();
                boolean success = response.body().getSuccess();
                if (code.equals("200") && success) {
                    Toast.makeText(AdultFromActivity.this, "审批完成", Toast.LENGTH_LONG).show();
                    AdultFromActivity.this.finish();
                }
            }

            @Override
            public void onFailure(String message) {

            }
        });
    }

    private void setToolbar() {
        toolbar.setNavigationIcon(R.drawable.ic_left_black_24dp);
        toolbar.setTitle("");

        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);

        toolbarBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String processInstanceId = applyForDTO.getProcessInstanceId();
                Intent intent = new Intent(AdultFromActivity.this, FlowRecordActivity.class);
                intent.putExtra("processInstanceId", processInstanceId);
                intent.putExtra("appType", appType);
                intent.putExtra("activityname", activityName);
                startActivity(intent);
            }
        });
    }


    private String getdivide(BigDecimal val1) {
        BigDecimal val2 = new BigDecimal(10000);
        BigDecimal decimal = val1.divide(val2);
        if (decimal.intValue() >= 1) {
            //方式一
            DecimalFormat df1 = new DecimalFormat("0.00");
            String str1 = df1.format(decimal.doubleValue());
            return str1 + "万根";
        } else {
            DecimalFormat df2 = new DecimalFormat("0.0");
            String str2 = df2.format(val1.doubleValue());
            return str2 + "根";
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                this.finish();
                return true;

        }
        return super.onOptionsItemSelected(item);
    }


    @OnClick({R.id.toolbar_btn, R.id.adult_back, R.id.adult_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_btn:
                String processInstanceId = applyForDTO.getProcessInstanceId();
                Intent intent = new Intent(AdultFromActivity.this, FlowRecordActivity.class);
                intent.putExtra("processInstanceId", processInstanceId);
                startActivity(intent);
                break;
            case R.id.adult_back:
                showCauseInputDialog(0);
                break;
            case R.id.adult_save:
                showCauseInputDialog(1);
                break;
        }
    }
}
